const Router = require("@koa/router")
const router = new Router()
const UserModel = require("../model/User")
const to = require("await-to-js").default

router.post("/login", async ctx => {
	const params = ctx.request.body
	if (ctx.empty(["account", "password"])) {
		return
	}
	var [err, user] = await to(
		UserModel.findOne({
			where: {
				account: params.account
			}
		})
	)
	if (err) {
		ctx.err("登录失败")
		return
	}
	if (!user) {
		ctx.err("用户不存在")
		return
	}
	// 密码加密验证
	const crypto = require("crypto")
	var password = crypto.createHash("md5").update(params.password).digest("hex")
	if (password !== user.password) {
		ctx.err("密码错误")
		return
	}
	// 生成token
	const { createToken } = require("../middleware/auth")
	const token = createToken(user.id)
	delete user.password
	ctx.suc("登录成功", { user, token })
})

router.post("/register", async ctx => {
	const params = ctx.request.body
	if (ctx.empty(["account", "password","name"])) {
		return
	}
	var [err, user] = await to(
		UserModel.findOne({
			where: {
				account: params.account
			},
			attributes: { exclude: ['password'] }
		})
	)
	if (user) {
		ctx.err("账号已存在")
		return
	}
	var [err, user] = await to(
		UserModel.create({
			name:params.name,
			account:params.account,
			password:params.password
		},{attributes: { exclude: ['password'] }})
	)
	if(err){
		ctx.err("注册失败",err)
		return
	}
	// 生成token
	const { createToken } = require("../middleware/auth")
	const token = createToken(user.id)
	ctx.suc("注册成功",{user,token})
})

module.exports = router.routes()